package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.adapter.ModelOrderAdapter;
import com.moyun.modelclass.adapter.SubmitOrderPriceAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.CashierDialog;
import com.moyun.modelclass.dialog.ConfigPrintParamsDialog;
import com.moyun.modelclass.http.api.AppModelListApi;
import com.moyun.modelclass.http.api.ConfigPrintParamsApi;
import com.moyun.modelclass.http.api.DefaultAddressApi;
import com.moyun.modelclass.http.api.OrderCreateApi;
import com.moyun.modelclass.http.api.OrderInfoApi;
import com.moyun.modelclass.http.api.OrderTrialApi;
import com.moyun.modelclass.http.api.PayParamsApi;
import com.moyun.modelclass.http.bean.AddressResponse;
import com.moyun.modelclass.http.bean.ModelResponse;
import com.moyun.modelclass.http.bean.OrderRequestResponse;
import com.moyun.modelclass.http.bean.WXPayRequest;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.listener.PayResult;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者：Meteor
 * tip：提交订单
 */
public class SubmitOrderActivity extends BaseActivity implements ModelOrderAdapter.OnItemSelectedChangedListener {
    private RelativeLayout rlSubmitOrderTop;
    private ImageView ivSubmitOrderBack;
    private RelativeLayout rlSubmitOrderAddress;
    private TextView tvSubmitOrderAddressNull;
    private TextView tvSubmitOrderName;
    private TextView tvSubmitOrderPhoneNumber;
    private TextView tvSubmitOrderAddress;
    private RecyclerView recyclerSubmitOrderModelList;
    private TextView tvSubmitOrderPrintOne;
    private TextView tvSubmitOrderPrintTwo;
    private TextView tvSubmitOrderPrintThree;
    private RecyclerView recyclerSubmitOrderPrice;
    private EditText etSubmitOrderNotes;//备注
    private TextView tvSubmitOrderAmountMoney;//合计总价
    private TextView tvSubmitOrderDiscountTitle;//折扣价格
    private TextView tvSubmitOrderBuy;//下单


    private List<String> articleIdList = new ArrayList<>();//文章id

    private AddressResponse mAddressInfo = null;//地址信息

    private ModelOrderAdapter ModelOrderAdapter;//模型适配器
    private List<OrderRequestResponse> requestBeanList = new ArrayList<>();//模型列表集合：计算价格
    private String mOrderId = "";//订单号

    //打印参数
    private List<ConfigPrintParamsApi.BeanInfo> configPrintParamsList = new ArrayList<>();
    private int positionOne = 0;//第一层的位置
    private int positionTwo = 0;//第二层的位置
    private int positionThree = 0;//第三层的位置
    private ConfigPrintParamsApi.BeanInfo printParamsThree = null;

    private SubmitOrderPriceAdapter submitOrderPriceAdapter = new SubmitOrderPriceAdapter();//价格

    private int mTotalPrice = 0;//总价
    private int mDeductionBalance = 0;//折扣
    private DecimalFormat df = new DecimalFormat("￥##0.00");
    public static final String KEY_ADDRESS_ID = "KEY_ADDRESS_ID";
    public static final int REQUEST_CODE = 1002;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                ToastUtils.showShort("支付成功" + payResult.getMemo());
                if (!mOrderId.isEmpty()) {
                    PayResultActivity.start(SubmitOrderActivity.this, true, mOrderId);
                }
                finish();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                ToastUtils.showShort("支付失败" + payResult.getMemo());
                if (!mOrderId.isEmpty()) {
                    PayResultActivity.start(SubmitOrderActivity.this, false, mOrderId);
                }
                finish();
            }
        }
    };

    public static void start(Context context, List<String> articleId) {
        Intent starter = new Intent(context, SubmitOrderActivity.class);
        starter.putExtra("articleId", (Serializable) articleId);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_submit_order;
    }

    @Override
    protected void assignViews() {
        rlSubmitOrderTop = (RelativeLayout) findViewById(R.id.rl_submit_order_top);
        ivSubmitOrderBack = (ImageView) findViewById(R.id.iv_submit_order_back);
        rlSubmitOrderAddress = (RelativeLayout) findViewById(R.id.rl_submit_order_address);
        tvSubmitOrderAddressNull = (TextView) findViewById(R.id.tv_submit_order_address_null);
        tvSubmitOrderName = (TextView) findViewById(R.id.tv_submit_order_name);
        tvSubmitOrderPhoneNumber = (TextView) findViewById(R.id.tv_submit_order_phone_number);
        tvSubmitOrderAddress = (TextView) findViewById(R.id.tv_submit_order_address);
        recyclerSubmitOrderModelList = (RecyclerView) findViewById(R.id.recycler_submit_order_model_list);
        tvSubmitOrderPrintOne = (TextView) findViewById(R.id.tv_submit_order_print_one);
        tvSubmitOrderPrintTwo = (TextView) findViewById(R.id.tv_submit_order_print_two);
        tvSubmitOrderPrintThree = (TextView) findViewById(R.id.tv_submit_order_print_three);
        recyclerSubmitOrderPrice = (RecyclerView) findViewById(R.id.recycler_submit_order_price);
        etSubmitOrderNotes = (EditText) findViewById(R.id.et_submit_order_notes);
        tvSubmitOrderAmountMoney = (TextView) findViewById(R.id.tv_submit_order_amount_money);
        tvSubmitOrderDiscountTitle = (TextView) findViewById(R.id.tv_submit_order_discount_title);
        tvSubmitOrderBuy = (TextView) findViewById(R.id.tv_submit_order_buy);

        StatusBarUtil.setPaddingSmart(this, rlSubmitOrderTop);

        ModelOrderAdapter = new ModelOrderAdapter(this);//模型适配器
        recyclerSubmitOrderModelList.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerSubmitOrderModelList.addItemDecoration(new DividerItemDecoration(mContext, Color.parseColor("#EFEFEF"), 1, 0, 0, true));
        ModelOrderAdapter.setOnItemSelectedChangedListener(this);
        recyclerSubmitOrderModelList.setAdapter(ModelOrderAdapter);

        recyclerSubmitOrderPrice.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerSubmitOrderPrice.setAdapter(submitOrderPriceAdapter);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivSubmitOrderBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(rlSubmitOrderAddress, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShippingAddressListActivity.start(SubmitOrderActivity.this, REQUEST_CODE);
            }
        });

        ClickUtils.applySingleDebouncing(tvSubmitOrderPrintOne, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (configPrintParamsList != null && configPrintParamsList.size() > 0) {
                    ConfigPrintParamsDialog dialog = ConfigPrintParamsDialog.getInstance(mActivity, "选择打印方式", positionOne, configPrintParamsList, new ConfigPrintParamsDialog.OnProjectTypeListener() {

                        @Override
                        public void content(ConfigPrintParamsApi.BeanInfo beanInfo, int position) {
                            tvSubmitOrderPrintOne.setText(beanInfo.paramLabel);
                            tvSubmitOrderPrintTwo.setText("");
                            tvSubmitOrderPrintThree.setText("");
                            printParamsThree = null;
                            positionOne = position;
                            positionTwo = 0;
                        }

                        @Override
                        public void cancel() {

                        }
                    }).builder();
                    dialog.show();
                }
            }
        });
        ClickUtils.applySingleDebouncing(tvSubmitOrderPrintTwo, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (positionOne == -1) {
                    ToastUtils.showShort("请先选择打印方式");
                    return;
                }

                if (configPrintParamsList != null && configPrintParamsList.size() > 0) {
                    ConfigPrintParamsDialog dialog = ConfigPrintParamsDialog.getInstance(mActivity, "选择打印材料", positionTwo, configPrintParamsList.get(positionOne).getOptionValue(), new ConfigPrintParamsDialog.OnProjectTypeListener() {
                        @Override
                        public void content(ConfigPrintParamsApi.BeanInfo beanInfo, int position) {
                            tvSubmitOrderPrintTwo.setText(beanInfo.paramLabel);
                            tvSubmitOrderPrintThree.setText("");
                            printParamsThree = null;
                            positionTwo = position;
                        }

                        @Override
                        public void cancel() {

                        }
                    }).builder();
                    dialog.show();
                }
            }
        });

        ClickUtils.applySingleDebouncing(tvSubmitOrderPrintThree, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (positionOne == -1) {
                    ToastUtils.showShort("请先选择打印方式");
                    return;
                }

                if (positionTwo == -1) {
                    ToastUtils.showShort("请先选择打印材料");
                    return;
                }

                if (configPrintParamsList != null && configPrintParamsList.size() > 0 && configPrintParamsList.get(positionOne).getOptionValue().size() > 0) {
                    ConfigPrintParamsDialog dialog = ConfigPrintParamsDialog.getInstance(mActivity, "选择材料类型", positionThree, configPrintParamsList.get(positionOne).getOptionValue().get(positionTwo).getOptionValue(), new ConfigPrintParamsDialog.OnProjectTypeListener() {

                        @Override
                        public void content(ConfigPrintParamsApi.BeanInfo beanInfo, int position) {
                            tvSubmitOrderPrintThree.setText(beanInfo.paramLabel);
                            printParamsThree = beanInfo;
                            positionThree = position;
                        }

                        @Override
                        public void cancel() {

                        }
                    }).builder();
                    dialog.show();
                } else {
                    ToastUtils.showShort("请先选择打印材料");
                }
            }
        });


        ClickUtils.applySingleDebouncing(tvSubmitOrderBuy, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initOrderCreateLog();
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        articleIdList = (List<String>) bundle.get("articleId");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initConfigPrintParamsLog();
        initModelListLog(articleIdList);
    }

    //通过模型id列表批量获取模型数据
    private void initModelListLog(List<String> modelIdList) {
        if (modelIdList.size() <= 0) {
            ToastUtils.showShort("模型id列表为空");
            return;
        }
        EasyHttp.post(this)
                .api(new AppModelListApi().setModelIdList(modelIdList).setScene(1))
                .request(new HttpCallback<HttpData<AppModelListApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<AppModelListApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            ModelOrderAdapter.setList(result.getData().getList());
                            requestBeanList.clear();
                            for (ModelResponse item : result.getData().getList()) {
                                OrderRequestResponse bean = new OrderRequestResponse();
                                bean.setModelId(item.getId());
                                bean.setCount(item.getAddCount());
                                bean.setSize(item.getModelSizeList().get(item.getSelectPosition()).getSize());
                                requestBeanList.add(bean);
                            }
                            defaultAddress();
                        }
                    }
                });
    }

    //获取用户默认地址
    private void defaultAddress() {
        EasyHttp.post(this)
                .api(new DefaultAddressApi())
                .request(new HttpCallback<HttpData<AddressResponse>>(this) {
                    @Override
                    public void onSucceed(HttpData<AddressResponse> result) {
                        if (result != null && result.getData() != null) {
                            mAddressInfo = result.getData();
                            setAddress(mAddressInfo);
                            initOrderTrialLog();
                        } else {
                            setAddress(null);
                        }
                    }
                });
    }

    //打印相关参数
    private void initConfigPrintParamsLog() {
        EasyHttp.post(this)
                .api(new ConfigPrintParamsApi())
                .request(new HttpCallback<HttpData<ConfigPrintParamsApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ConfigPrintParamsApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            configPrintParamsList = result.getData().getList();
                            tvSubmitOrderPrintOne.setText(configPrintParamsList.get(0).paramLabel);
                            tvSubmitOrderPrintTwo.setText(configPrintParamsList.get(0).getOptionValue().get(0).getParamLabel());
                            tvSubmitOrderPrintThree.setText(configPrintParamsList.get(0).getOptionValue().get(0).getOptionValue().get(0).getParamLabel());
                            printParamsThree = configPrintParamsList.get(0).getOptionValue().get(0).getOptionValue().get(0);
                        }
                    }
                });
    }

    //预计算商品价格
    private void initOrderTrialLog() {
        if (mAddressInfo == null) {
            ToastUtils.showShort("请先选择收货地址");
            return;
        }

        if (requestBeanList == null || requestBeanList.size() <= 0) {
            ToastUtils.showShort("请先选择尺寸");
            return;
        }
        if (printParamsThree == null) {
            ToastUtils.showShort("请先选择打印参数");
            return;
        }

        EasyHttp.post(this)
                .api(new OrderTrialApi().setAddressId(mAddressInfo.getId()).setModelList(requestBeanList).setPrintParams(printParamsThree.paramId))
                .request(new HttpCallback<HttpData<OrderTrialApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<OrderTrialApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            mTotalPrice = result.getData().getTotalPrice();
                            mDeductionBalance = result.getData().getDeductionBalance();
                            tvSubmitOrderAmountMoney.setText(df.format(result.getData().getTotalPrice() * 0.01));//总价格
                            tvSubmitOrderDiscountTitle.setText("余额抵扣：" + df.format(result.getData().getDeductionBalance() * 0.01));//抵扣余额，单位为分

                            submitOrderPriceAdapter.setList(result.getData().getList());
                        }
                    }
                });
    }

    //订单创建
    private void initOrderCreateLog() {
        if (mAddressInfo == null) {
            ToastUtils.showShort("请先选择收货地址");
            return;
        }

        if (requestBeanList == null || requestBeanList.size() <= 0) {
            ToastUtils.showShort("请先选择尺寸");
            return;
        }

        if (printParamsThree == null) {
            ToastUtils.showShort("请先选择打印参数");
            return;
        }
        EasyHttp.post(this)
                .api(new OrderCreateApi().setAddressId(mAddressInfo.getId()).setModelList(requestBeanList)
                        .setPrintParams(printParamsThree.paramId)
                        .setRemark(etSubmitOrderNotes.getText().toString())
                        .setScene("3")
                        .setDeductionBalance(mDeductionBalance))
                .request(new HttpCallback<HttpData<OrderCreateApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<OrderCreateApi.Bean> orderCreateResult) {
                        if (orderCreateResult != null && orderCreateResult.getData() != null) {
                            EasyHttp.post(SubmitOrderActivity.this)
                                    .api(new OrderInfoApi().setPayOrderId(orderCreateResult.getData().getPayOrderId()))
                                    .request(new HttpCallback<HttpData<OrderInfoApi.Bean>>(SubmitOrderActivity.this) {
                                        @Override
                                        public void onSucceed(HttpData<OrderInfoApi.Bean> orderInfoResult) {
                                            if (orderInfoResult != null && orderInfoResult.getData() != null) {
                                                mOrderId = orderInfoResult.getData().getOrderId();
                                                OrderInfoApi.ChannelBean channelBean = orderInfoResult.getData().getChannelList().get(1);
                                                CashierDialog dialog = CashierDialog.getInstance(SubmitOrderActivity.this, mTotalPrice, channelBean, new CashierDialog.OnCashierListener() {
                                                    @Override
                                                    public void pay() {
                                                        EasyHttp.post(SubmitOrderActivity.this)
                                                                .api(new PayParamsApi()
                                                                        .setPayOrderId(orderCreateResult.getData().getPayOrderId())
                                                                        .setChannelId(channelBean.getChannelId()))
                                                                .request(new HttpCallback<HttpData<PayParamsApi.Bean>>(SubmitOrderActivity.this) {
                                                                    @Override
                                                                    public void onSucceed(HttpData<PayParamsApi.Bean> payParamsResult) {
                                                                        if (payParamsResult != null && payParamsResult.getData() != null) {
//                                                                            IWXAPI api = WXAPIFactory.createWXAPI(mActivity, BaseConfig.WX_APPID, true);
//                                                                            boolean clientValid = api.isWXAppInstalled();
//                                                                            if (clientValid) {
////                                                                                WXPayRequest wxPayRequest = GsonUtils.fromJson(payParamsResult.getData().getWxParams(), WXPayRequest.class);
//                                                                                PayReq request = new PayReq();
//                                                                                request.appId = payParamsResult.getData().getWxParams().getAppId();
//                                                                                request.partnerId = payParamsResult.getData().getWxParams().getPartnerid();
//                                                                                request.prepayId = payParamsResult.getData().getWxParams().getPrepayid();
//                                                                                request.packageValue = payParamsResult.getData().getWxParams().getPackagee();
//                                                                                request.nonceStr = payParamsResult.getData().getWxParams().getNoncestr();
//                                                                                request.timeStamp = payParamsResult.getData().getWxParams().getTimestamp();
//                                                                                request.sign = payParamsResult.getData().getWxParams().getSign();
//                                                                                api.sendReq(request);
//                                                                            } else {
//                                                                                ToastUtils.showShort("请安装微信客户端");
//                                                                            }

                                                                            final String orderInfo = payParamsResult.getData().getAliParams().getOrderStr();   // 订单信息
                                                                            Runnable payRunnable = new Runnable() {
                                                                                @Override
                                                                                public void run() {
                                                                                    PayTask alipay = new PayTask(SubmitOrderActivity.this);
                                                                                    Map<String, String> result = alipay.payV2(orderInfo, true);
                                                                                    Message msg = new Message();
                                                                                    msg.obj = result;
                                                                                    mHandler.sendMessage(msg);
                                                                                }
                                                                            };
                                                                            // 必须异步调用
                                                                            Thread payThread = new Thread(payRunnable);
                                                                            payThread.start();
                                                                        }
                                                                    }
                                                                });
                                                    }

                                                    @Override
                                                    public void cancel() {
                                                        //查看详情
                                                        OrderDetailsActivity.start(SubmitOrderActivity.this, orderCreateResult.getData().getOrderId());
                                                        finish();
                                                    }
                                                }).builder();
                                                dialog.show();


                                            }
                                        }
                                    });


                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SubmitOrderActivity.REQUEST_CODE) {
                AddressResponse addressInfo = (AddressResponse) data.getSerializableExtra(SubmitOrderActivity.KEY_ADDRESS_ID);
                if (addressInfo != null) {
                    mAddressInfo = addressInfo;
                    setAddress(mAddressInfo);
                    initOrderTrialLog();
                }
            }
        }
    }

    //处理收货地址UI
    @SuppressLint("SetTextI18n")
    private void setAddress(AddressResponse mAddressInfo) {
        if (mAddressInfo != null) {
            tvSubmitOrderAddressNull.setVisibility(View.INVISIBLE);
            tvSubmitOrderName.setVisibility(View.VISIBLE);
            tvSubmitOrderPhoneNumber.setVisibility(View.VISIBLE);
            tvSubmitOrderAddress.setVisibility(View.VISIBLE);

            tvSubmitOrderName.setText(mAddressInfo.getName());
            tvSubmitOrderPhoneNumber.setText(mAddressInfo.getMobile());
            tvSubmitOrderAddress.setText(mAddressInfo.getProvince() + " " + mAddressInfo.getCity() + " " + mAddressInfo.getArea() + " " + mAddressInfo.getDetail());
        } else {
            tvSubmitOrderAddressNull.setVisibility(View.VISIBLE);
            tvSubmitOrderName.setVisibility(View.INVISIBLE);
            tvSubmitOrderPhoneNumber.setVisibility(View.INVISIBLE);
            tvSubmitOrderAddress.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onItemSelected() {
        List<ModelResponse> modelList = ModelOrderAdapter.getData();
        requestBeanList.clear();
        for (ModelResponse item : modelList) {
            OrderRequestResponse bean = new OrderRequestResponse();
            bean.setModelId(item.getId());
            bean.setCount(item.getAddCount());
            bean.setSize(item.getModelSizeList().get(item.getSelectPosition()).getSize());
            requestBeanList.add(bean);
        }
        initOrderTrialLog();
    }
}
